<template>
	<view class="container">
		<!-- <view class="title">预付金额</view> -->
		<div style="padding: 24upx;">
			<view class="prepayment_box">
				<image class="gold" src="../../static/images/hotWater/gold.png" style="width: 200upx;height: 200upx;" mode="scaleToFill">
				</image>
				<view class="title row">
					预付金额
				</view>
				<view class="prepayment row">
					￥{{advance}}
				</view>
				<view class="tip row">
					<uni-icons type="info" color="#FFF"></uni-icons> 消费金额将从预付金额中扣除，剩余金额将返还支付账户
				</view>
			</view>
		</div>
		<view class="payinfo_box">
			<view class="title">商户信息</view>
			<view class="info_msg">
				<uni-icons type="shop" size="20" color="#999"></uni-icons> &nbsp;&nbsp;{{machineMsg.merchantName}}
			</view>
			<view class="info_msg">
				<uni-icons type="location-filled" size="20" color="#999"></uni-icons>
				{{`${machineMsg.orgName} ${machineMsg.deviceNo}号机`}}<!--  -->
			</view>
			<view class="info_msg" style="color: #007AFF;">
				<uni-icons type="help-filled" size="20" color="#007AFF"></uni-icons>单价：{{machineMsg.rate}}分/L
			</view>
		</view>
		<view class="paytype">
			<view class="title">支付方式</view>
			<radio-group @change="radioChange">
				<!-- #ifdef MP-WEIXIN -->
				<view class="">
					<!-- <label class="uni-list-cell uni-list-cell-pd"> -->
					<label class="payitem">
						<view class="payitem_title">
							<image class="pay_icon" src="../../static/images/hotWater/pay_wechat.png" mode="scaleToFill"></image>微信支付
						</view>
						<radio :value="1" :checked="1 == current" color="#007AFF" />
					</label>
					<!-- </label> -->
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-ALIPAY -->
				<view class="">
					<!-- <label class="uni-list-cell uni-list-cell-pd"> -->
					<label class="payitem">
						<view class="payitem_title">
							<image class="pay_icon" src="../../static/images/hotWater/pay_mypay.png" mode="scaleToFill"></image>支付宝支付
						</view>
						<radio :value="2" :checked="2 == current" color="#007AFF" />
					</label>
					<!-- </label> -->
				</view>
				<!-- #endif -->
				<view class="" v-if="user.icCardNo != null && user.icCardNo != undefined &&  user.icCardNo != ''">
					<!-- <label class="uni-list-cell uni-list-cell-pd"> -->
					<label class="payitem">
						<view class="payitem_title">
							<image class="pay_icon" src="../../static/images/hotWater/pay_card.png" mode="scaleToFill"></image>校园IC卡支付
						</view>
						<radio :value="3" :checked="3 == current" color="#007AFF" />
					</label>
					<!-- </label> -->
				</view>
			</radio-group>
		</view>
		<view class="submit" style="padding: 42upx 24rpx;">
			<!-- #ifdef MP-WEIXIN -->
			<button :disabled="createOrdering" class="submitBtn"
				@click="payment">确认支付</button><!--  open-type='getPhoneNumber' -->
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<button :disabled="createOrdering" class="submitBtn"
				@click="payment">确认支付</button><!--  open-type='getAuthorize' scope='phoneNumber' -->
			<!-- #endif -->
			<!-- <button :disabled="createOrdering" class="submitBtn" @click="testpayment()">测试支付</button> -->
		</view>
	</view>
</template>

<script>
	import {
		getOpenid,
		queryCreateOrder,
		payForIcCard,
		getAccessToken
	} from '../../common/api/hot_water.js'
	import {
		WX_APPID,
		ALI_APPID
	} from '../../common/utils/config.js'
	let _this;
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				current: 1,
				// #endif
				// #ifdef MP-ALIPAY
				current: 2,
				// #endif
				advancTime: 20, //开阀时间
				advanceAmount: 1, //预付金额
				machineMsg: {}, //订单设备机构等信息
				user: uni.getStorageSync('userInfo'),
				createOrdering: false,
			}
		},
		onLoad(option) {
			console.log('userInfo:' + getOpenid)
			_this = this;
			_this.advancTime = option.advancTime;
			_this.advanceAmount = option.advanceAmount;
			_this.machineMsg = JSON.parse(option.machineMsg);
			_this.machineMsg['code'] = option.code;
			if ( option.userInfo ){
				_this.user = JSON.parse(option.userInfo)
				uni.setStorageSync('userInfo', option.userInfo)
			}
		},
		methods: {
			radioChange: function(evt) {
				this.current = evt.target.value
			},
			payment() {
				if (!this.createOrdering) {
					this.createOrdering = true
					uni.showLoading({
						title: "启动支付中"
					})
					if (this.current == 1) {
						_this.payForWeChatPay()
					} else if (this.current == 2) {
						_this.payForAliPay()
						// my.getPhoneNumber({
						// 	success: (res) => {
						// 		// console.log(res)
						// 		_this.payForAliPay(res)
						// 	},
						// 	fail: (res) => {
						// 		uni.showModal({
						// 			title: '提示',
						// 			content: '支付失败，获取手机号码失败~',
						// 			confirmColor: "#007AFF",
						// 			showCancel: false
						// 		})
						// 	},
						// });
					} else {
						_this.payForIcCard()
					}
				}
			},
			// IC 卡消费 注：卡消费预付时间用分钟
			payForIcCard() {
				payForIcCard({
					"advancTime": parseFloat(_this.advancTime),
					"advanceAmount": parseFloat(_this.advanceAmount),
					"cardNo": _this.user.icCardNo,
					"machNo": _this.machineMsg.deviceNo,
					"orgId": _this.user.orgId,
					"expand": 0,
					// "payDate": "string",
					..._this.machineMsg
				}).then(res => {
					if (res.code === 0 && res.data.resultCode === 0) {
						uni.setStorageSync('consumptionId', res.data.consumptionId)
						uni.setStorageSync('guid', _this.machineMsg.guid)
						uni.setStorageSync('payType', _this.current)
						// 授权发送服务信息
						// #ifdef MP-WEIXIN
						wx.requestSubscribeMessage({
							tmplIds: ['pEoxYDsxf6d_k4uAhpaktpYTm3yWTZOZ4NqY1YH1sOY'],
							success(res) {
								console.log(res)
							}
						})
						// #endif
						uni.redirectTo({
							url: `./consuming?advancTime=${_this.advancTime}&advanceAmount=${_this.advanceAmount}&payType=${_this.current}&machineMsg=${JSON.stringify(_this.machineMsg)}`,
							success() {}
						})
					} else {
						_this.createOrdering = false
						uni.hideLoading()
						uni.showModal({
							showCancel: false,
							title: '提示',
							content: res.data.resultMsg || res.msg,
							confirmColor: "#007AFF",
						})
					}
				}).catch(err => {
					_this.createOrdering = false
					uni.hideLoading()
					uni.showModal({
						title: '提示',
						content: '支付失败，请稍后重试',
						confirmColor: "#007AFF",
						showCancel: false
					})
				})
			},
			// 微信消费 注：卡消费预付时间用分钟
			payForWeChatPay() {
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log(loginRes)
						getOpenid({
							code: loginRes.code,
							xappId: WX_APPID
						}).then(resOpenid => {
							if (resOpenid.resultCode == 0 || resOpenid.code == 0){
								_this.createOrder(resOpenid.data.openid)
								// 之前获取手机号码的需求
								// deWxInfo({
								// 	encryptedData: phoneData.detail.encryptedData,
								// 	iv: phoneData.detail.iv,
								// 	sessionKey: resOpenid.data.session_key
								// }).then(res => {
								// 	if (res.resultCode === 0 && res.phoneNumber != '') {
								// 		_this.createOrder(resOpenid.data.openid, res.phoneNumber)
								// 	} else {
								// 		_this.createOrdering = false
								// 		uni.showModal({
								// 			title: '提示',
								// 			content: '支付失败，获取手机号码失败~',
								// 			confirmColor: "#007AFF",
								// 			showCancel: false
								// 		})
								// 	}
								// })
							}else {
								uni.showModal({
									title: '提示',
									content: '支付失败,'+resOpenid.resultMsg || resOpenid.msg,
									confirmColor: "#007AFF",
									showCancel: false
								})
								_this.createOrdering = false
								uni.hideLoading()
							}
						}).catch(err => {
							console.log(err)
						})
					}
				});
			},
			// changePhone(){
			// 	return new Promise((resolve, reject)=>{
			// 		let phone = uni.getStorageSync('wechatPhone');
			// 		if(){

			// 		}
			// 	})

			// },
			// 支付宝消费 注：卡消费预付时间用分钟
			payForAliPay() {
				uni.login({
					scopes: 'auth_base',
					success: function(codeRes) {
						getAccessToken({
							code: codeRes.authCode,
							xappId: ALI_APPID
						}).then((resAliUserId) => {
							_this.createOrder(resAliUserId.data.aliUserId)
							// deAliInfo({
							// 	...JSON.parse(phoneData.response)
							// }).then(res => {
							// 	let data = JSON.parse( res.data )
							// 	if (res.resultCode === 0 && res.phoneNumber != '') {
							// 		// user['alipayUserId'] = resAliUserId.data.aliUserId
							// 		_this.createOrder(resAliUserId.data.aliUserId, data
							// 			.mobile)
							// 	} else {
							// 		_this.createOrdering = false
							// 		uni.showModal({
							// 			title: '提示',
							// 			content: '支付失败，获取手机号码失败~',
							// 			confirmColor: "#007AFF",
							// 			showCancel: false
							// 		})
							// 	}
							// })
						})
					}
				});
			},
			createOrder(id, phone) {
				if(!_this.user.userId){
					uni.showModal({
						title: '提示',
						content: '无法获取完整设备信息，请使用【微信扫一扫】重新扫码用水',
						showCancel: false,
						confirmColor: "#007AFF"
					})
					uni.hideLoading()
					_this.createOrdering = false
					return
				}
				queryCreateOrder({
					// 创建订单
					//#ifdef MP-WEIXIN
					xappId: WX_APPID,
					openId: id,
					//#endif
					//#ifdef MP-ALIPAY
					aliPayUserId: id,
					//#endif
					flag: _this.current,
					advanceAmount: parseFloat(_this.advanceAmount),
					// advanceAmount: 0.05,
					userId: _this.user.userId,
					advanceTime: parseFloat(_this.advancTime) * 60,
					// phone,
					..._this.machineMsg
				}).then(res => {
					if (res.code === 0) {
						uni.setStorageSync('consumptionId', res.data.consumptionId)
						// #ifdef MP-WEIXIN
						// 微信支付功能
						wx.requestPayment({
							timeStamp: (res.data.timeStamp).toString(),
							nonceStr: (res.data.nonceStr).toString(),
							package: (res.data.packages).toString(),
							signType: (res.data.signType).toString(),
							paySign: (res.data.paySign).toString(), //微信、支付宝订单数据
							success: function(resWP) {
								if (resWP.errMsg === "requestPayment:ok") {
									// uni.setStorageSync('consumptionId', res.data.consumptionId)
									uni.setStorageSync('guid', _this.machineMsg.guid)
									uni.setStorageSync('payType', _this.current)
									// 授权发送服务信息
									wx.requestSubscribeMessage({
										tmplIds: [
											'pEoxYDsxf6d_k4uAhpaktpYTm3yWTZOZ4NqY1YH1sOY'
										],
										success(res) {
											console.log(res)
										}
									})
									// 跳转回到小交小程序
									uni.navigateBackMiniProgram({
									  extraData: {
									    'consumptionId': res.data.consumptionId,
										'advancTime': _this.advancTime,
										'advanceAmount': _this.advanceAmount,
										'payType': _this.current,
										'machineMsg': JSON.stringify(_this.machineMsg)
									  }
									})
									uni.redirectTo({
										url: `./consuming?advancTime=${_this.advancTime}&advanceAmount=${_this.advanceAmount}&payType=${_this.current}&machineMsg=${JSON.stringify(_this.machineMsg)}`,
										success() {}
									})
								}
							},
							fail: function(errP) {
								if (errP.errMsg === "requestPayment:fail cancel") {
									uni.hideLoading()
									_this.createOrdering = false
									uni.showModal({
										title: '提示',
										content: '支付失败，您取消了支付！',
										confirmColor: "#007AFF",
										showCancel: false
									})
								}
							}
						});
						// #endif
						// #ifdef MP-ALIPAY
						my.tradePay({
							tradeNO: res.data.payResponseNo,
							success: function(resAP) {
								if (resAP.resultCode === "9000") {
									// uni.setStorageSync('consumptionId', res.data.consumptionId)
									uni.setStorageSync('guid', _this.machineMsg.guid)
									uni.setStorageSync('payType', _this.current)
									// 跳转回到小交小程序
									uni.navigateBackMiniProgram({
									  extraData: {
									    'consumptionId': res.data.consumptionId,
										'advancTime': _this.advancTime,
										'advanceAmount': _this.advanceAmount,
										'payType': _this.current,
										'machineMsg': JSON.stringify(_this.machineMsg)
									  }
									})
									// 授权发送服务信息
									uni.redirectTo({
										url: `./consuming?advancTime=${_this.advancTime}&advanceAmount=${_this.advanceAmount}&payType=${_this.current}&machineMsg=${JSON.stringify(_this.machineMsg)}`,
										success() {}
									})
								} else if (resAP.resultCode === "6001") {
									uni.hideLoading()
									_this.createOrdering = false
									uni.showModal({
										title: '提示',
										content: '支付失败，您取消了支付！',
										confirmColor: "#007AFF",
										showCancel: false
									})
								}
							},
							fail: function(errAp) {
								console.log(errAp)
							},
						});
						// #endif
					} else {
						_this.createOrdering = false
						uni.hideLoading()
						let msg = res.msg
						// if( res.code == 502 ){
						// 	msg =res.msg + "，请使用绑定联通号码的微信进行支付，或绑定校园IC卡进行消费"
						// }else if( res.code == 501 ){
						// 	msg = "获取手机号码失败，请联系管理员进行处理"
						// }else{
							// msg = res.msg
						// }
						uni.showModal({
							title: '提示',
							content: msg,
							confirmColor: "#007AFF",
							showCancel: false
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			// testpayment(){
			// 	my.tradePay({
			// 		tradeNO: '2020061822001402851449122720',
			// 		success: function(resAP) {
			// 			if(resAP.resultCode === "9000"){
			// 				uni.setStorageSync('consumptionId', res.data.consumptionId)
			// 				uni.setStorageSync('guid', _this.machineMsg.guid)
			// 				uni.setStorageSync('payType', _this.current)
			// 				// 授权发送服务信息
			// 				uni.redirectTo({
			// 					url: `./consuming?advancTime=${_this.advancTime}&advanceAmount=${_this.advanceAmount}&payType=${_this.current}&machineMsg=${JSON.stringify(_this.machineMsg)}`,
			// 					success() {}
			// 				})
			// 			}else if(resAP.resultCode === "6001"){
			// 				_this.createOrdering = false
			// 				uni.showModal({
			// 					title: '提示',
			// 					content: '支付失败，您取消了支付！',
			// 					confirmColor: "#007AFF",
			// 					showCancel: false
			// 				})
			// 			}
			// 		},
			// 		fail: function(errAp) {
			// 		},
			// 	});
			// }
		},
		computed: {
			advance: function() {
				return parseFloat(this.advanceAmount).toFixed(2)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		background-color: #F1F0F5;
		height: 100vh;
	}
	.title {
		font-size: 40upx;
		font-weight: bold;
		padding: 12upx 48upx;
	}

	.prepayment_box {
		background-color: #007AFF;
		background-image: linear-gradient(135deg, #00c4ff, #014dff);
		box-shadow: 0px 2px 8px 0px #78d5ff;
		color: #FFF;
		position: relative;
		text-align: center;
		padding: 24upx 0;
		margin-bottom: 24upx;
		border-radius: 10upx;
		overflow: hidden;

		.gold {
			position: absolute;
			opacity: 0.3;
			bottom: -50rpx;
			left: 20rpx;

		}

		.row {
			padding: 12upx 0;
		}

		.title {
			font-size: 30upx;
			// font-weight: 600;
		}

		.prepayment {
			font-size: 80upx;
			// font-weight: 600;
		}

		.tip {
			display: flex;
			justify-content: center;
			flex-direction: row;
			font-size: 22upx;
			align-items: center;
		}
	}

	.paytype,
	.payinfo_box {
		background-color: #FFF;
		// border-radius: 10upx;
		padding: 24upx 0;
		margin-bottom: 24rpx;
		box-shadow: 0px 2px 8px 0px #ededed;

		.payitem,
		.info_msg {
			display: flex;
			justify-content: space-between;
			flex-direction: row;
			padding: 24upx 42upx;

			.payitem_title {
				display: flex;
				justify-content: space-between;
				flex-direction: row;

				// font-size: 32upx;
				.pay_icon {
					width: 50upx;
					height: 50upx;
					margin-right: 12upx;
				}
			}
		}

		.info_msg {
			justify-content: flex-start;
			color: #999;
			font-size: 30upx;
			padding: 0 42upx;
			padding-top: 12upx;
		}
	}
</style>
